package website

import (
	"gitee.com/Luna-CY/hui-hui/server/http/response"
	"github.com/gin-gonic/gin"
	"sort"
)

type WebsitesResponse struct {
	response.BaseListResponse[WebsitesWebsite]
}

type WebsitesWebsite struct {
	Hostname string `json:"hostname" validate:"required"` // 站点域名
	Tls      struct {
		Enable   bool   `json:"enable" validate:"required"`    // 是否启用TLS
		Custom   bool   `json:"custom" validate:"required"`    // 自定义TLS证书
		CertPath string `json:"cert_path" validate:"required"` // 证书路径
		KeyPath  string `json:"key_path" validate:"required"`  // 私钥路径
	} `json:"tls" validate:"required"` // TLS配置
	Reverses []WebsitesReverse `json:"reverses" validate:"required"` // 反向代理配置
}

type WebsitesReverse struct {
	Path   string `json:"path" validate:"required"`   // 匹配路径
	Target string `json:"target" validate:"required"` // 目标地址
}

func (cls *Website) Websites(_ *gin.Context) (int, any, error) {
	var websites = cls.caddy.GetConfig().Websites

	var res = WebsitesResponse{}
	res.Total = int64(len(websites))
	for hostname, website := range websites {
		var item = WebsitesWebsite{Hostname: hostname, Reverses: make([]WebsitesReverse, 0)}
		item.Tls.Enable = website.Tls.Enable
		item.Tls.Custom = website.Tls.Custom
		item.Tls.CertPath = website.Tls.CertPath
		item.Tls.KeyPath = website.Tls.KeyPath

		for _, reverse := range website.Reverses {
			item.Reverses = append(item.Reverses, WebsitesReverse{Path: reverse.Path, Target: reverse.Target})
		}

		res.Data = append(res.Data, item)
	}

	sort.Slice(res.Data, func(i, j int) bool {
		return res.Data[i].Hostname < res.Data[j].Hostname
	})

	return response.Ok, res, nil
}
